package core

import (
	"encoding/json"
	"fmt"
	"github.com/google/gopacket"
	"log"
	"os"
	"path/filepath"
	"sync"
	"time"
)

type PacketInfo struct {
	DeviceName  string                   `json:"-"`
	Timestamp   time.Time                `json:"timestamp"`
	SrcMAC      string                   `json:"src_mac,omitempty"`
	DstMAC      string                   `json:"dst_mac,omitempty"`
	SrcIP       string                   `json:"src_ip,omitempty"`
	SrcIPinfo   IpInfo                   `json:"src_ipinfo,omitempty"`
	DstIP       string                   `json:"dst_ip,omitempty"`
	DstIPinfo   IpInfo                   `json:"dst_ipinfo,omitempty"`
	Protocol    string                   `json:"protocol"`
	SrcPort     uint16                   `json:"src_port,omitempty"`
	DstPort     uint16                   `json:"dst_port,omitempty"`
	Payload     []byte                   `json:"payload,omitempty"` // Base64编码后存储
	PayloadLen  int                      `json:"payload_len"`
	Host        string                   `json:"host,omitempty"`
	ProcessName string                   `json:"process_name,omitempty"`
	Metadata    *gopacket.PacketMetadata `json:"-"`
}

var (
	fileMutexes = make(map[string]*sync.Mutex)
	globalMutex sync.Mutex
)

// AppendToJSON Deprecated : 这个方法已经迁移到了Saver
func (p *PacketInfo) AppendToJSON(filename string) error {

	globalMutex.Lock()
	mu, exists := fileMutexes[filename]
	if !exists {
		mu = &sync.Mutex{}
		fileMutexes[filename] = mu
	}
	defer globalMutex.Unlock()

	// 锁定文件操作
	mu.Lock()
	defer mu.Unlock()

	// 1. 序列化为JSON
	data, err := json.Marshal(p)
	if err != nil {
		return fmt.Errorf("JSON序列化失败: %w", err)
	}
	data = append(data, '\n') // 添加换行符作为分隔

	// 获得路径
	root, _ := getProjectRoot()
	outputPathOnlyDir := filepath.Join(root, "Output", filename)

	fmt.Println(outputPathOnlyDir)
	// 创建文件夹
	err = createNotExistDir(outputPathOnlyDir)
	if err != nil {
		fmt.Println("%s 文件夹创建失败", outputPathOnlyDir)
		return fmt.Errorf("创建文件夹失败: %w", err)
	}

	currentTime := time.Now()
	outputPath := filepath.Join(outputPathOnlyDir, fmt.Sprintf("%s.json", currentTime.Format("2006-01-02")))
	//fmt.Println("outputPath:", outputPath)

	// 2. 打开文件（追加模式）
	file, err := os.OpenFile(outputPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
	if err != nil {
		return fmt.Errorf("打开文件失败: %w", err)
	}

	defer func() {
		if err := safeClose(file); err != nil {
			log.Printf("警告: %v", err)
		}
	}()

	// 3. 写入数据
	if _, err := file.Write(data); err != nil {
		return fmt.Errorf("写入文件失败: %w", err)
	}

	return nil
}
